/*
 * AddUserFrame.java
 *
 * Created on __DATE__, __TIME__
 */

package tw.com.jinwei.ui;

import it.cnr.imaa.essi.lablib.gui.checkboxtree.CheckboxTree;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.mchange.v1.util.ArrayUtils;

import tw.com.jinwei.db.Function;
import tw.com.jinwei.db.User;
import tw.com.jinwei.service.Authorize;
import tw.com.jinwei.utils.Constants;
import tw.com.jinwei.utils.ContextUtils;
import tw.com.jinwei.utils.LogHelper;

/**
 * 
 * @author __USER__
 */
public class AddUserFrame extends javax.swing.JInternalFrame {

	/** Creates new form AddUserFrame */
	public AddUserFrame() {
		super(Constants.TITLE_SYSTEM_USER_ADD, true, true, true, true);
		initComponents();
		this.unfoldPermissionTree();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		idLabel = new javax.swing.JLabel();
		pwdLabel = new javax.swing.JLabel();
		idTextField = new javax.swing.JTextField();
		passwordField = new javax.swing.JPasswordField();
		jButton1 = new javax.swing.JButton();
		jScrollPane1 = new javax.swing.JScrollPane();
		jTree1 = new CheckboxTree();

		idLabel.setText("\u4f7f\u7528\u8005");

		pwdLabel.setText("\u5bc6\u78bc");

		idTextField.setColumns(50);

		passwordField.setColumns(50);

		jButton1.setText("\u78ba\u5b9a");
		jButton1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton1ActionPerformed(evt);
			}
		});

		jScrollPane1.setViewportView(jTree1);

		org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout
				.setHorizontalGroup(layout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(
								layout
										.createSequentialGroup()
										.addContainerGap()
										.add(
												layout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.LEADING)
														.add(
																layout
																		.createSequentialGroup()
																		.add(
																				layout
																						.createParallelGroup(
																								org.jdesktop.layout.GroupLayout.LEADING)
																						.add(
																								idLabel)
																						.add(
																								pwdLabel))
																		.add(
																				18,
																				18,
																				18)
																		.add(
																				layout
																						.createParallelGroup(
																								org.jdesktop.layout.GroupLayout.LEADING,
																								false)
																						.add(
																								passwordField)
																						.add(
																								idTextField)
																						.add(
																								jScrollPane1)))
														.add(jButton1))
										.addContainerGap(19, Short.MAX_VALUE)));
		layout
				.setVerticalGroup(layout
						.createParallelGroup(
								org.jdesktop.layout.GroupLayout.LEADING)
						.add(
								layout
										.createSequentialGroup()
										.addContainerGap()
										.add(
												layout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.BASELINE)
														.add(idLabel)
														.add(
																idTextField,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
										.add(18, 18, 18)
										.add(
												layout
														.createParallelGroup(
																org.jdesktop.layout.GroupLayout.BASELINE)
														.add(pwdLabel)
														.add(
																passwordField,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
																org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
																org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
										.addPreferredGap(
												org.jdesktop.layout.LayoutStyle.RELATED)
										.add(
												jScrollPane1,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
												org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
												org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												org.jdesktop.layout.LayoutStyle.UNRELATED)
										.add(jButton1).addContainerGap(40,
												Short.MAX_VALUE)));

		pack();
	}// </editor-fold>

	// GEN-END:initComponents

	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
		if (log.isDebugEnabled()) {
			log.debug(new StringBuilder("action command == ").append(evt
					.getActionCommand()));
		}
		if (StringUtils.isEmpty(idTextField.getText())
				|| StringUtils.isEmpty(passwordField.getText())) {
			JOptionPane.showMessageDialog(this, Constants.MSG_SYSTEM_USER_ERROR);
			return;
		}
		User user = new User();
		user.setName(idTextField.getText());
		user.setPassword(passwordField.getText());
		Set functions = new HashSet();
		TreePath[] tp = jTree1.getCheckingPaths();
		for (int i = 0; i < tp.length; i++) {
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) tp[i]
					.getLastPathComponent();
			Function func = (Function) node.getUserObject();
			functions.add(func);
		}
		Authorize authorize = (Authorize) ContextUtils.getContext().getBean(
				"authorize");
		log
				.info(new StringBuilder("create user name == ").append(
						user.getName()).append(", password == ").append(
						user.getName()));
		log.info(new StringBuilder("permission == ").append(ArrayUtils
				.toString(functions.toArray())));
		user.setFunctions(functions);
		authorize.saveNewUser(user);
		idTextField.setText("");
		passwordField.setText("");
		jTree1.clearChecking();
	}

	// GEN-BEGIN:variables
	// Variables declaration - do not modify
	private javax.swing.JLabel idLabel;
	private javax.swing.JTextField idTextField;
	private javax.swing.JButton jButton1;
	private javax.swing.JScrollPane jScrollPane1;
	private CheckboxTree jTree1;
	private javax.swing.JPasswordField passwordField;
	private javax.swing.JLabel pwdLabel;
	// End of variables declaration//GEN-END:variables

	private Logger log = LogHelper.getLog(getClass());

	private void unfoldPermissionTree() {
		DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");

		Authorize authorize = (Authorize) ContextUtils.getContext().getBean(
				"authorize");
		List parentFunction = authorize.findParentFunctions();
		if (log.isDebugEnabled()) {
			log.debug(new StringBuilder("parent count == ")
					.append(parentFunction.size()));
		}
		for (int i = 0; i < parentFunction.size(); i++) {
			Function func = (Function) parentFunction.get(i);
			DefaultMutableTreeNode parent = new DefaultMutableTreeNode(func);
			Iterator iterator = func.getFunctions().iterator();
			while (iterator.hasNext()) {
				Function subFunc = (Function) iterator.next();
				DefaultMutableTreeNode child = new DefaultMutableTreeNode(
						subFunc);
				parent.add(child);
			}
			root.add(parent);
		}
		TreeModel treeModel = new DefaultTreeModel(root);
		jTree1.setModel(treeModel);
		jTree1.setRootVisible(false);
	}

}